package com.haredot.security;

import com.haredot.vo.R;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 当用户没有登录的时候，进行的逻辑处理
 */
public class JsonAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 返回一个 JSON , 提示用户 没有登录 ， 401
        new MappingJackson2HttpMessageConverter()
                .write(R.fail(R.StatusCode.NOT_AUTH).build(), MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
    }
}
